package com.usefullc.chatgpt.filter;

import com.usefullc.chatgpt.constants.ChatgptConstants;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.accept.PathExtensionContentNegotiationStrategy;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class ChatgptResourceHttpRequestHandler extends ResourceHttpRequestHandler {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
//    public final static String ATTR_FILE = "NON-STATIC-FILE";
    public final static String MEDIA_TYPE = "mediaType";
    private PathExtensionContentNegotiationStrategy contentNegotiationStrategy;

    private List<String> matchPathUrls = new ArrayList<>();

    public void addMatchPathUrls(String pathUrl){
        matchPathUrls.add(pathUrl);
    }

    public ChatgptResourceHttpRequestHandler() {
//        super(HttpMethod.GET.name(), HttpMethod.HEAD.name());
        setSupportedMethods("GET","POST","HEAD","OPTIONS","PUT");
    }



    @Override
    protected Resource getResource(HttpServletRequest request) throws IOException {
        String requestURI = request.getRequestURI();
        boolean match = false;
        for (String matchPathUrl : matchPathUrls) {
            if(StringUtils.startsWithIgnoreCase(requestURI,matchPathUrl)){
                match = true;
                break;
            }
        }
        if(match){
            String name = FilenameUtils.getName(requestURI);
            String parentPath = StringUtils.remove(requestURI, name);
            String filePath = ChatgptConstants.RESOURCE_DIR + parentPath;
            File dir = new File(filePath);
            boolean exists = dir.exists();
            if(!exists){
                logger.warn("cann't found resource={},dir={}",request.getRequestURL(),dir);
                return null;
            }
            Collection<File> files = FileUtils.listFiles(dir, new PrefixFileFilter(name), DirectoryFileFilter.INSTANCE);
            if (CollectionUtils.isEmpty(files)) {
                logger.warn("cann't found resource={}",request.getRequestURL());
                return null;
            }else{
                File file = files.stream().findFirst().get();
//                if(requestURI.equalsIgnoreCase("/Video/GetVideoLis")){
//                    //返回内容篡改
//                    String fileContent = FileUtils.readFileToString(file, "utf-8");
//
//                }
                return new FileSystemResource(file);

            }

//            FileUtils.getFile(TestConstants.RESOURCE_DIR,)

        }else{
            return super.getResource(request);
        }
    }

    //    public void init(){
//        this.contentNegotiationStrategy = initContentNegotiationStrategy();
//        setSupportedMethods("GET","POST","HEAD","OPTIONS","PUT");
//    }
    @Override
    public List<Resource> getLocations() {

        List<Resource> locations = super.getLocations();
        if(CollectionUtils.isEmpty(locations)){
            locations = new ArrayList<>();
        }
        locations.add(new FileSystemResource(ChatgptConstants.RESOURCE_DIR));
        return locations;
    }

    @Override
    protected MediaType getMediaType(HttpServletRequest request, Resource resource) {
        Assert.notNull(resource, "Resource must not be null");
//        MediaType mediaType = null;
        Object attribute = request.getAttribute(MEDIA_TYPE);
        String filename = resource.getFilename();
        if(attribute != null && StringUtils.isNotEmpty(attribute.toString())){
            filename = "abc."+attribute.toString();
        }
//        else{
//            String extension = StringUtils.getFilenameExtension(filename);
//        if (extension != null) {
//            mediaType = contentNegotiationStrategy.(extension);
//        }
//        if (mediaType == null) {
//        }
//            return mediaType;

//        }
        return MediaTypeFactory.getMediaType(filename).orElse(null);
    }


    //    @Override
//    protected Resource getResource(HttpServletRequest request) {
//        final Path filePath = (Path) request.getAttribute(ATTR_FILE);
//        return new FileSystemResource(filePath);
//    }
}
